import { defineStore } from 'pinia';

/**
 * 作者：马小雅
 * 时间：2024-05-23
 * 功能：购物车状态管理
 */

interface CartItem {
  id: number;
  name: string;
  price: number;
  quantity: number;
}

export const MaUseCartStore = defineStore('cart', {
  state: () => ({
    items: [] as CartItem[]
  }),
  persist: true,
  getters: {
    MaTotalPrice: (state) => {
      return state.items.reduce((sum, item) => sum + item.price * item.quantity, 0);
    },
    MaTotalQuantity: (state) => {
      return state.items.reduce((sum, item) => sum + item.quantity, 0);
    }
  },
  actions: {
    MaAddToCart(product: CartItem) {
      const existing = this.items.find(item => item.id === product.id);
      if (existing) {
        existing.quantity += 1;
      } else {
        this.items.push({ ...product, quantity: 1 });
      }
    },
    MaRemoveFromCart(productId: number) {
      this.items = this.items.filter(item => item.id !== productId);
    }
  }
}
);